/* Filename: abcd.c
 * No.89.线程-互斥量
 * Description:4个线程分别打印abcd，且按顺序，持续5秒
 * $ gcc -Wall abcd.c -o abcd -lpthread
 * Last modified: humble 2020-09-02 10:06:45
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <unistd.h>

#define THRNUM (4)

static pthread_mutex_t mut[THRNUM];

static int next(int n)
{
    if(n + 1 == THRNUM){
        return 0;
    }
    return n + 1;
}


static void *thr_abcd(void *p)
{
    int n = (int)p;
    int c = 'a' + (int)p;

    while(1){
        pthread_mutex_lock(mut + n); //死等着抢属于自己的锁
        write(1, &c, 1);
        pthread_mutex_unlock(mut + next(n)); //放开下一个人的锁
    }
    pthread_exit(NULL);
}

int main(int argc, char **argv)
{
    int i, err;
    pthread_t tid[THRNUM];

    for(i = 0; i < THRNUM; i++)
    {
        pthread_mutex_init(mut + i, NULL);
        pthread_mutex_lock(mut + i); //初始化完，立刻抢锁
        err = pthread_create(tid + i, NULL, thr_abcd, (void *)i);
        if(err){
            //while(--i < 0){ pthread_join(tid[i - LEFT], NULL); } //未测
            fprintf(stderr, "pthread_create():%s\n", strerror(err));
            exit(1);
        }
    }
    //线程创建完毕时全部锁都抢到了

    pthread_mutex_unlock(mut + 0); //放开a的锁
    alarm(5); //5秒钟后进程被信号杀死

    for(i = 0; i < THRNUM; i++)
    {
        pthread_join(tid[i], NULL);
    }
    return 0;
}
